<?php
namespace app\controllers;

use app\models\AdminModel;
use wlcat\http\controllers\Controller;

class AdminController extends Controller {
    public function __construct($controller, $action)
    {
        parent::__construct($controller, $action);
        if (!$this->checkLogin())
        {
            redirect('login');
        }
        $this->assign('username', $this->request->input('session.user'));
    }
    public function checkLogin()
    {
        $uid  = $this->request->input('session.uid', null);
        $time = $this->request->input('session.loginExpire', null);
        return $uid > 0 && $time > time();
    }
    public function index()
    {
        $list   = (new AdminModel())->selectAll();
        $this->assign('list', $list);
        $this->display();
    }
    public function view($id = null)
    {
        $item = (new AdminModel)->select($id);

        $this->assign('info', $item);
        $this->display();
    }

    public function add()
    {
        $this->display();
    }
    public function insert()
    {
        $name           = $this->request->input('post.user');
        $password       = $this->request->input('post.password');
        $password       = empty($password) ? "123456" : $password;
        $password       = getPassword($password);

        (new AdminModel())->add(array(
            'user'          => $name,
            'password'      => $password[0],
            'rand'          => $password[1]
        ));
        $this->success('插入成功', admin_url('admin/index'), 1);
    }

    public function update()
    {
        $id = $this->request->input('post.id');
        if (!intval($id) > 0)
        {
            echo 'id错误';
            die;
        }

        $data['user']           = $this->request->input('post.user');
        $password               = $this->request->input('post.password');
        if (!empty($password))
        {
            $password           = getPassword($password);
            $data['password']   = $password[0];
            $data['rand']       = $password[1];
        }
        (new AdminModel())->update($id, $data);
        $this->success('更新成功', admin_url('admin/index'), 1);
    }

    public function destroy($id)
    {
        $item = (new AdminModel)->select($id);
        if ($item['is_super'] == 1)
        {
            $this->error('超级管理员不得删除');
            exit;
        }
        (new AdminModel())->delete($id);
        $this->success('删除成功', admin_url('admin/index'), 1);
    }

    public function logout()
    {
        $this->request->setInput('session.uid', null);
        $this->request->setInput('session.loginExpire', null);
        redirect('login');
    }
}